//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.AcceptanceTests
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Net;
    using ServiceModel.Client;
    using ServiceModel.Contract;
    using TestScenarios;
    using TestScenarios.CustomClient;
    using Xunit;

    public class PreflightTestScenarios
    {
        private static readonly StandardEndpointFactory endpointFactory = new StandardEndpointFactory();
        private const string Name = "Test";

        [Fact]
        public void AspNetWithNoSecurity()
        {
            var endpoint = endpointFactory.CreateUnsecureHttpDescription(Name, BuildBaseUri(AspNetScenarioName.AspNetNoSecurity));
            TestScenario(endpoint);
        }

        [Fact]
        public void AspNetWithWindowsAuthentication()
        {
            var endpoint = endpointFactory.CreateWindowsAuthenticationEndpointDescription(Name, BuildBaseUri(AspNetScenarioName.AspNetWindowsAuth));
            TestScenario(endpoint);
        }

        [Fact]
        public void AspNetWithWindowsAuthenticationDeniesProperly()
        {
            var endpoint = endpointFactory.CreateWindowsAuthenticationEndpointDescription(Name, BuildBaseUri(AspNetScenarioName.AspNetWindowsAuthDeny));
            var exception = Assert.Throws<WebException>(() => TestScenario(endpoint));
            Assert.Equal(HttpStatusCode.Unauthorized, ((HttpWebResponse) exception.Response).StatusCode);
        }

        [Fact]
        public void AspNetWithCustomAuthentication()
        {
            var endpoint = CustomAuthClientFactory.CreateEndpointDescription(BuildBaseUri(AspNetScenarioName.AspNetCustomAuth));
            TestScenario(endpoint);
        }

        [Fact]
        public void AspNetWithPreflightSecurity()
        {
            var endpoint = endpointFactory.CreateSecureHttpDescription(Name,
                                                                       BuildBaseUri(AspNetScenarioName.AspNetPreflightAuth),
                                                                       Constants.Certificate);
            TestScenario(endpoint);
        }

        [Fact]
        public void WindowsServiceWithPreflightSecurity()
        {
            var uri = new Uri(string.Format("http://{0}:{1}/", Environment.MachineName, Constants.ServicePort));
            var endpoint = endpointFactory.CreateSecureHttpDescription(Name, uri, Constants.Certificate);
            TestScenario(endpoint);
        }

        [Fact]
        public void WindowsServiceWithWindowsSecurity()
        {
            var uri = new Uri(string.Format("http://{0}:{1}/", Environment.MachineName, Constants.WinAuthServicePort));
            var endpoint = endpointFactory.CreateWindowsAuthenticationEndpointDescription(Name, uri);
            TestScenario(endpoint);
        }

        public void AcsSecurityTest()
        {
            var uri = new Uri(string.Format("http://{0}:{1}/", Environment.MachineName, Constants.AcsAuthServicePort));
            var endpoint = endpointFactory.CreateAcsSecuredServiceDescription(Name, uri, new Uri(ACSSettings.AcsUri), new Uri(ACSSettings.Realm), ACSSettings.Username, ACSSettings.Password);
            TestScenario(endpoint);
        }

        private static Uri BuildBaseUri(AspNetScenarioName scenarioName)
        {
            return new Uri(string.Format("http://{0}:71/{1}", Environment.MachineName, scenarioName));
        }

        private static void TestScenario(EndpointDescription endpoint)
        {
            try
            {
                var client = ClientFactory.Create().CreateClient(endpoint);
                var host = client.GetHostDetails();
                var result = client.RunPreflightCheck();
                VerifyHostDescription(host);
                VerifyResults(result);
            }
            catch(WebException exception)
            {
                if (exception.Response != null)
                {
                    var responseStream = exception.Response.GetResponseStream();
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            Console.WriteLine(reader.ReadToEnd());
                        }
                    }
                    else
                    {
                        Console.WriteLine("No response stream available");
                    }
                }
                else
                {
                    Console.WriteLine("No Response Available");
                }
                throw;
            }
        }

        private static void VerifyHostDescription(HostDetails host)
        {
            VerifyDescription(host.Description);
            var categories = host.VerificationCategories.ToList();
            Assert.Equal(3, host.VerificationCategories.Count);
            Assert.Contains("Services", categories);
            Assert.Contains("Critical", categories);
            Assert.Contains("Resources", categories);
        }

        private static void VerifyDescription(Description description)
        {
            Assert.Equal(description.Name, Constants.ApplicationName);
            Assert.Equal(description.Version, Constants.ApplicationVersion);
            Assert.Equal(description.Category, Constants.ApplicationCategory);
        }

        private static void VerifyResults(PreflightCheck check)
        {
            Assert.True(check.Passed);
            VerifyDescription(check.Description);
            Assert.Equal(3, check.Categories.Count());
        }
    }
}
